package cz.fimuni.pa165.frontend.restservice;

import com.google.gson.Gson;
import cz.fimuni.pa165.backendapi.dto.CarDTO;
import cz.fimuni.pa165.backendapi.dto.ReservationDTO;
import cz.fimuni.pa165.backendapi.facade.ServiceFacade;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author Ondřej Myška
 */
@Controller
@RequestMapping("/rest/car")
public class CarRestService implements CarRestServiceInterface {

    @Autowired
    private ServiceFacade serviceFacade;
    @Autowired
    private Gson gson;

    @RequestMapping(value = "/add", method = RequestMethod.POST, headers = "Content-Type=application/json")
    @ResponseBody
    @Override
    public ResponseEntity<String> addtCar(@RequestBody String json) {

        CarDTO carDTO = gson.fromJson(json, CarDTO.class);

        if (carDTO.getNumberOfSeats() > 0 && !carDTO.getColour().isEmpty() && !carDTO.getSpz().isEmpty()) {
            Authentication auth = new UsernamePasswordAuthenticationToken("rest", "rest") ;
            SecurityContextHolder.getContext().setAuthentication(auth);
            serviceFacade.addCar(carDTO);
            SecurityContextHolder.getContext().setAuthentication(null);
            return new ResponseEntity<String>(HttpStatus.ACCEPTED);
        } else {
            return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
        }

    }

    @RequestMapping(value = "/getall", method = RequestMethod.GET)
    public @ResponseBody
    @Override
    ResponseEntity<String> getAllCars() {
        Authentication auth = new UsernamePasswordAuthenticationToken("rest", "rest") ;
        SecurityContextHolder.getContext().setAuthentication(auth);
        String response = gson.toJson(serviceFacade.getAllCars());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        SecurityContextHolder.getContext().setAuthentication(null);
        return new ResponseEntity<String>(response, headers, HttpStatus.OK);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public @ResponseBody
    @Override
    ResponseEntity<String> deleteCar(@PathVariable String id) {

        try {
            Authentication auth = new UsernamePasswordAuthenticationToken("rest", "rest") ;
            SecurityContextHolder.getContext().setAuthentication(auth);
            serviceFacade.removeCar(serviceFacade.find(Long.parseLong(id)));
            return new ResponseEntity<String>(HttpStatus.OK);
        } catch (JpaSystemException e) {
            List<ReservationDTO> dtoList = serviceFacade.getAllReservations();
            for (int i = 0; i < dtoList.size(); i++) {
                if (dtoList.get(i).getCar().getId() == Long.parseLong(id)) {
                    try {
                        serviceFacade.removeReservation(dtoList.get(i));
                        serviceFacade.removeCar(serviceFacade.find(Long.parseLong(id)));
                        SecurityContextHolder.getContext().setAuthentication(null);
                        return new ResponseEntity<String>(HttpStatus.OK);
                    } catch (JpaSystemException ex) {
                        SecurityContextHolder.getContext().setAuthentication(null);
                        return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
                    }
                }
            }

        }
        SecurityContextHolder.getContext().setAuthentication(null);
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, headers = "Content-Type=application/json")
    @ResponseBody
    @Override
    public ResponseEntity<String> updateCar(@RequestBody String json) {

        CarDTO carDTO = gson.fromJson(json, CarDTO.class);

        if (carDTO.getNumberOfSeats() > 0 && !carDTO.getColour().isEmpty() && !carDTO.getSpz().isEmpty()) {
            Authentication auth = new UsernamePasswordAuthenticationToken("rest", "rest") ;
            SecurityContextHolder.getContext().setAuthentication(auth);
            serviceFacade.updateCar(carDTO);
            SecurityContextHolder.getContext().setAuthentication(null);
            return new ResponseEntity<String>(HttpStatus.ACCEPTED);
        } else {
            return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
        }

    }

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ResponseBody
    @Override
    public ResponseEntity<String> pokus(@PathVariable("id") Long id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        Authentication auth = new UsernamePasswordAuthenticationToken("rest", "rest") ;
        SecurityContextHolder.getContext().setAuthentication(auth);
        String car = gson.toJson(serviceFacade.find(id));
        SecurityContextHolder.getContext().setAuthentication(null);
        return new ResponseEntity<String>(car, headers, HttpStatus.OK);
    }
}
